package net.csdn.business.notify.api.action;

import com.alibaba.fastjson2.JSON;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.notify.common.enums.ProcessStatusEnum;
import net.csdn.business.notify.common.model.vo.NotifyResponseVO;
import net.csdn.business.notify.common.pipeline.BusinessProcess;
import net.csdn.business.notify.common.pipeline.ProcessContext;
import net.csdn.business.notify.common.pipeline.domain.*;
import net.csdn.business.notify.api.service.ISendMqService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;


/**
 * @ClassName SendPrivateMqAction
 * @Description 将消息发送到MQ
 * @Author zhangyl
 * @Date 2023/12/5 17:23
 */
@Slf4j
@Service
public class SendPrivateMqAction implements BusinessProcess<SendPrivateTaskModel> {


    @Autowired
    private ISendMqService sendMqService;

    @Value("${ali.mq.notify.private.topic:NOTIFY_PRIVATE_CHANNEL}")
    private String privateTopic;

    @Override
    public void process(ProcessContext<SendPrivateTaskModel> context) {
        int total=context.getTotal();
        NotifyResponseVO response=context.getResponse();
        Map<String,String> failMap=response.getFail();
        SendPrivateTaskModel sendTaskModel = context.getProcessModel();
        List<PrivateTaskInfo> taskInfoList = sendTaskModel.getTaskInfo();
        if(taskInfoList==null||taskInfoList.size()==0){
            response.setStatus(ProcessStatusEnum.FAIL);
            context.setNeedBreak(true);
            log.info("send private mq cancel,taskinfo is null");
            return;
        }
        for (PrivateTaskInfo task:taskInfoList){
            String batchNum=task.getBatchNum();
            try {
                String message = JSON.toJSONString(task);
                sendMqService.send(privateTopic, message, "private");
            } catch (Exception e) {
                log.error("send mq notify {} fail! e:{},params:{}", Throwables.getStackTraceAsString(e)
                        ,JSON.toJSONString(task));
                failMap.put(batchNum, ProcessStatusEnum.SEND_MQ_ERROR.getMsg());
            }
        }
        //处理结束，标记任务状态
        if(failMap.size()>0){
            response.setStatus(failMap.size()<total? ProcessStatusEnum.PART_SUCCESS:ProcessStatusEnum.FAIL);
        }
        context.setNeedBreak(true);
    }

}
